Answer:

The complete program is given below.

Complete Factorial Program

This program is suitable for copying into a program editor, compiling and running in the usual way. Animal brains, such as those in humans, learn best when they see things happen. Run the program. See things happen.

import  java.util.Scanner;

// User enters integer N.  
// The program calculates N factorial.
//
class factorial
{
  public static void main (String[] args ) 
  {
    Scanner scan = new Scanner( System.in );
    long N, fact = 1; 

    System.out.print( "Enter N: " );
    N = scan.nextLong();

    if ( N >= 0 )
    {
      while ( N > 1 )    
      {
        fact = fact * N;
        N    = N - 1;
      }
      System.out.println( "factorial is " + fact );
    }
    else
    {
      System.out.println("N must be zero or greater");
    }
  }
}

Here are several runs of the program. It is amazing how quickly factorial becomes enormous.

factorial

Warning! Factorial becomes so big, so fast, that 20! is as large as this program can calculate. However, it will give you an answer for N larger than 20. But the answer will be wrong. This is because when a result requires more bits than a variable has, the variable ends up with garbage. This behavior is called overflow and is a frequent problem with computers.

QUESTION 10:

Think about removing the two innermost braces of the program (the { after the while and its matching } ). Keep everything else about the program the same. What would happen?